﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using EasyClassWEBAPI.EntityClass;
using EasyClassWEBAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EasyClassWEBAPI.Controllers
{
    [Route("Comment")]
    [ApiController]
    public class CommentController : ControllerBase
    {
        private EasyClassContext db;
        public CommentController(EasyClassContext context)
        {
            this.db = context;
        }
        /// <summary>
        /// 添加评论 Post:Comment/add
        /// PostID：帖子/问题的ID，boby评论的内容
        /// 注意：Header里面需要包含Token来标识用户
        /// </summary>
        /// <param name="PostID"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        [HttpPost("Add")]
        public async Task<IActionResult> AddComment(int PostID,[FromForm]string body)
        {
            try
            {
                //获取Token标识的用户(即为评论的发布者)
                string token = this.Request.Headers["Authorization"];
                var user = await db.Users.FirstOrDefaultAsync(o => o.Token == token);
                if (user == null) return NotFound("User didn't exist!");

                Post post = await db.Posts.FirstOrDefaultAsync(o => o.PostID == PostID);
                if (post == null) return NotFound("Post didn't exist!");

                Comment newComment = new Comment(user.UserAccount, body);
                newComment.Post = post;
                db.Comments.Add(newComment);
                await db.SaveChangesAsync();

                return Ok("Add Comment Successfully!");
            }catch(Exception error)
            {
                return BadRequest($"Add Comment Failed. Reson:{error.Message}");
            }
        }
    }
}
